import * as lodash from "lodash";
import * as databaseConfig from "../database/config";
const CryptoJS = require('crypto-js');
const fs = require('fs');
const sharp = require('sharp');

/**
 * 字符串自增
 * @param {*} str
 * @returns 
 */
export function strAddOne(str: string) {
  if (!str) return "";
  const totalLens = str.length;
  const num = lodash.parseInt(str) + 1;
  const preStr = new Array(totalLens - (num + "").length).fill("0").join("");
  return preStr + "" + num;
}

/**
 * 和初始化数据合并
 * @param {*} obj 传入对象数据
 * @param {*} fields 合并的基数据
 * @returns 
 */
export function joinDefaultFields(obj: any, fields: string) {
  if (!obj) return {};
  if (!databaseConfig[fields]) {
    return {};
  }
  const _obj = JSON.parse(JSON.stringify(databaseConfig[fields]));
  Object.assign(_obj, obj);
  return _obj;
}

/**
 * 将对象中的驼峰命名修改为 _
 * @param data 
 * @returns 
 */
export function dealWithKey(data: any) {
  const obj = {};
  if (Object.keys(data).length === 0) return obj;
  for (const key in data) {
    const newKey = key.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
    obj[newKey] = data[key];
  }
  return obj;
}

/**
 * 加密
 * @param text 明文
 * @param key 密钥
 * @returns 
 */
export function encrypt(text: string, key = "dxj") {
  return CryptoJS.AES.encrypt(text, key).toString();
}

/**
 * 校验手机号
 * @param phone 手机号
 */
export function validatePhone(phone: string) {
  const regex = /^(13[0-9]|14[5-9]|15[0-3,5-9]|16[5-6]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;
  return regex.test(phone);
}

/**
 * 校验指定路径是否存在文件夹，没有及创建
 * @param dirPath 文件夹路径
 */
export async function valideDirname(dirPath: string) {
  return new Promise(async (resolve, reject) => {
    try {
      fs.access(dirPath, fs.constants.F_OK, async (err) => {
        if (err) {
          try {
            await fs.mkdirSync(dirPath, { recursive: true });
            resolve(true);
          } catch (mkdirErr) {
            reject(mkdirErr);
          }
        } else {
          resolve(true);
        }
      });
    } catch (error) {
      return Promise.reject(`An error occurred while checking for the directory:${dirPath}, error: ${error}`);
    }
  });
};

/**
 * 压缩复制图片并保存到指定路径 - 【标记 - 有些方式复制图片后，内存一直保留，删除不了】
 * @param filepath 当前文件路径
 * @param targetPath 目标文件路径
 */
export async function copyFile(filepath: string, targetPath: string) {
  return new Promise(async (resolve, reject) => {
    try {
      const metadata = await sharp(filepath).metadata();
      const width = metadata.width > metadata.height ? 1000 : null;
      const height = metadata.width < metadata.height ? 1000 : null;

      const readStream = fs.createReadStream(filepath);
      const writeStream = fs.createWriteStream(targetPath);
      const transform = sharp()
        .pipe(readStream)
        .pipe(sharp().resize(width, height).toFormat('jpeg', { compression: 75 }))
        .pipe(writeStream);
      transform.on('finish', (res: any) => {
        readStream.destroy();
        writeStream.destroy();
        resolve(res);
      });
      transform.on('error', (err) => {
        reject(err);
      });
    } catch (err) {
      reject(err);
    }
  });
};

/**
 * 删除指定路径文件
 * @param filePath 文件路径
 */
export function deleteFile(filePath: string) {
  return new Promise((resolve, reject) => {
    fs.unlink(filePath, (err) => {
      if (err) {
        reject('Error deleting file:' + err);
      } else {
        resolve('File deleted successfully.');
      }
    });
  });
}
